import { Alert, Tabs, Input, Select } from 'antd';
import React, { useState, useCallback, useRef } from 'react';
import QRCode from 'qrcode.react';
import Captcha from 'react-captcha-code';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { useIntl, connect, FormattedMessage } from 'umi';
import type { Dispatch } from 'umi';
import type { StateType } from '@/models/login';
import type { LoginParamsType } from '@/services/login';
import type { ConnectState } from '@/models/connect';
import login_userid from '../../../../public/icons/login_userid.png';
import login_pwd from '../../../../public/icons/login_pwd.png';
import login_role from '../../../../public/icons/login_role.png';
import login_verify from '../../../../public/icons/login_verify.png';
import styles from './index.less';

const { Option } = Select;

export type LoginProps = {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

// function onChange(value: any) {
//   console.log(`selected ${value}`);
// }

// function onBlur() {
//   console.log('blur');
// }

// function onFocus() {
//   console.log('focus');
// }

// function onSearch(val: any) {
//   console.log('search:', val);
// }

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status, type: loginType } = userLogin;
  const [type, setType] = useState<string>('account');
  const intl = useIntl();

  const handleSubmit = (values: LoginParamsType) => {
    const { dispatch } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values, type },
    });
  };
  const handleChange = useCallback((captcha) => {
    console.log('captcha:', captcha);
  }, []);

  const captchaRef: any = useRef<HTMLCanvasElement>();

  // 刷新验证码
  // const handleClick = () => {
  //   (captchaRef as any).current.refresh();
  // };

  return (
    <div className={styles.main}>
      <Tabs activeKey={type} onChange={setType}>
        <Tabs.TabPane
          key="account"
          className={styles.tabFirst}
          tab={intl.formatMessage({
            id: 'pages.login.accountLogin.login',
            defaultMessage: '账号登录',
          })}
        />
        <Tabs.TabPane
          key="mobile"
          className={styles.tabTwo}
          tab={intl.formatMessage({
            id: 'pages.login.phoneLogin.login',
            defaultMessage: '二维码登录',
          })}
        />
      </Tabs>

      {/* 账户登录 */}
      {type === 'account' && (
        <>
          <ProForm
            initialValues={{
              autoLogin: true,
            }}
            submitter={{
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                loading: submitting,
                size: 'large',
                style: {
                  width: '80%',
                  marginLeft: '10%',
                  marginTop: '12px',
                  borderRadius: '8px',
                },
              },
            }}
            onFinish={(values) => {
              handleSubmit(values as LoginParamsType);
              return Promise.resolve();
            }}
          >
            {status === 'error' && loginType === 'account' && !submitting && (
              <LoginMessage
                content={intl.formatMessage({
                  id: 'pages.login.accountLogin.errorMessage',
                  defaultMessage: '账户或密码错误（admin/ant.design)',
                })}
              />
            )}
            <ProFormText
              name="username"
              className={styles.login_input}
              fieldProps={{
                size: 'large',
                prefix: <img className={styles.input_icon} alt="logo" src={login_userid} />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.identity.placeholder',
                defaultMessage: '身份证号',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.identity.required"
                      defaultMessage="请输入身份证号!"
                    />
                  ),
                },
              ]}
            />
            <select>
              <option value="volvo">Volvo</option>
              <option value="saab">Saab</option>
              <option value="opel">Opel</option>
              <option value="audi">Audi</option>
            </select>
            <Select
              defaultValue=""
              size="large"
              style={{ width: '100%' }}
              bordered={true}
              className={styles.InputSelect}
            >
              <Option value="角色1">角色1</Option>
              <Option value="角色2">角色2</Option>
              <Option value="角色3">角色3</Option>
            </Select>

            <Input.Group compact className={styles.login_role_group}>
              <div className={styles.login_role_div}>
                <img className={styles.login_role_icon} alt="logo" src={login_role} />
              </div>
              {/* <ProFormText
                name="role"
                style={{ width: '1%' }}
                className={styles.login_role_input}
                fieldProps={{
                  size: 'large',
                  prefix: <img className={styles.input_icon} alt="logo" src={login_role} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.role.placeholder',
                  defaultMessage: '角色',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.role.required"
                        defaultMessage="请输入角色!"
                      />
                    ),
                  },
                ]}
              /> */}
              <Select
                defaultValue=""
                size="large"
                placeholder="Select a person"
                style={{ width: '315px', borderLeft: '0px' }}
                bordered={true}
                className={styles.InputSelect}
              >
                <Option value="角色1">角色1</Option>
                <Option value="角色2">角色2</Option>
                <Option value="角色3">角色3</Option>
              </Select>
            </Input.Group>

            <Input.Group compact className={styles.login_role_group}>
              <ProFormText
                name="role"
                style={{ width: '70%' }}
                className={styles.login_role_input}
                fieldProps={{
                  size: 'large',
                  prefix: <img className={styles.input_icon} alt="logo" src={login_role} />,
                  // prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.role.placeholder',
                  defaultMessage: '角色',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.role.required"
                        defaultMessage="请输入角色!"
                      />
                    ),
                  },
                ]}
              />
              <Select
                defaultValue=""
                size="large"
                style={{ width: '25%' }}
                bordered={true}
                className={styles.InputSelect}
              >
                <Option value="角色1">角色1</Option>
                <Option value="角色2">角色2</Option>
                <Option value="角色3">角色3</Option>
              </Select>
            </Input.Group>

            <ProFormText
              name="role"
              className={styles.login_input}
              fieldProps={{
                size: 'large',
                prefix: <img className={styles.input_icon} alt="logo" src={login_role} />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.role.placeholder',
                defaultMessage: '角色',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage id="pages.login.role.required" defaultMessage="请输入角色!" />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              className={styles.login_input}
              fieldProps={{
                size: 'large',
                prefix: <img className={styles.input_icon} alt="logo" src={login_pwd} />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.pwd.placeholder',
                defaultMessage: '密码',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage id="pages.login.pwd.required" defaultMessage="请输入密码！" />
                  ),
                },
              ]}
            />

            <div className={styles.captcha_dev}>
              <ProFormText
                name="captcha"
                className={styles.captcha_small}
                fieldProps={{
                  size: 'large',
                  prefix: <img className={styles.input_icon} alt="logo" src={login_verify} />,
                }}
                style={{ width: 100 }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.captcha.placeholder',
                  defaultMessage: '请输入验证码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码!"
                      />
                    ),
                  },
                ]}
              />
              <Captcha
                className={styles.captcha_code}
                ref={captchaRef}
                bgColor="white"
                charNum={4}
                onChange={handleChange}
              />
            </div>

            <div
              style={{
                marginBottom: 24,
              }}
            >
              <a
                style={{
                  float: 'left',
                  color: '#fc714c',
                }}
              >
                <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
              </a>
              <a
                style={{
                  float: 'right',
                  fontWeight: 'bold',
                }}
              >
                <FormattedMessage id="pages.login.findNewAccount" defaultMessage="找回新账户" />
              </a>
            </div>
          </ProForm>
        </>
      )}

      {status === 'error' && loginType === 'mobile' && !submitting && (
        <LoginMessage content="二维码识别错误" />
      )}
      {type === 'mobile' && (
        <>
          {/* 验证码 */}
          {/* <Captcha ref={captchaRef} charNum={6} onChange={handleChange} /> */}
          <QRCode
            id="qrCode"
            value="https://www.jianshu.com/u/992656e8a8a6"
            size={400} // 二维码的大小
            // fgColor="#000000" // 二维码的颜色
            includeMargin={true}
            style={{ margin: '0px' }}
            imageSettings={{
              // 二维码中间的logo图片
              // src: '../../publish/favicon.png',
              src: 'http://cdn.yxxit.com/research/favicon.png',
              height: 60,
              width: 60,
              excavate: true, // 中间图片所在的位置是否镂空
            }}
          />
        </>
      )}
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
